/**
 * 
 */
package ict.kth.se.web.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	
	private static final int SECONDS_IN_YEAR = 31536000;
	

	/**
	 * Helper method to set cookie
	 * @param name
	 * @param value
	 * @param response
	 */
	public static void addCookie(String name, String value,
			HttpServletResponse response) {
		Cookie c = new Cookie(name, value);
		c.setPath("/");
		c.setMaxAge(SECONDS_IN_YEAR);
		response.addCookie(c);
	}
	
	/**
	 * Helper method to get value of cookie
	 * 
	 * @param request
	 * @param cookieName
	 *            name of cookie
	 * @return value of cookie
	 */
	public static String getCookieValue(final HttpServletRequest request,
			final String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals(cookieName)) {
					return c.getValue();
				}
			}
		}
		return null;
	}
	
	/**
	 * Helper method to get value of cookie
	 * 
	 * @param request
	 * @param cookieName
	 *            name of cookie
	 * @return value of cookie
	 */
	public static Long getCookieValueAsLong(final HttpServletRequest request,
			final String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals(cookieName)) {
					return Long.parseLong(c.getValue());
				}
			}
		}
		return null;
	}

	/**
	 * Helper method to remove cookie
	 * 
	 * @param request
	 * @param request
	 * @param cookieName
	 *            name of cookie
	 */
	public static void removeCookie(HttpServletRequest request,
			HttpServletResponse response, String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals(cookieName)) {
					c.setMaxAge(0);
					response.addCookie(c);
				}
			}
		}
	}

}
